package indi.mozping.kafka.producer;

import indi.mozping.config.MyConfig;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.springframework.stereotype.Component;

/**
 * @author by mozping
 * @Classname MyProducer
 * @Description RocketMq生产者，生产者依赖于生产者组，并且需要连接 nameServer
 * @Date 2020/9/30 10:45
 */
@Component
public class MyProducer {

    /**
     * 生产组,生产者必须在生产组内
     */
    private String producerGroup = "my_producer";

    /**
     * 端口
     */
    private String nameServer = MyConfig.NAME_SERVER;


    private DefaultMQProducer producer;

    public MyProducer() {
        //示例生产者
        producer = new DefaultMQProducer(producerGroup);
        //不开启vip通道 开通口端口会减2
        producer.setVipChannelEnabled(false);
        //绑定name server
        producer.setNamesrvAddr(MyConfig.NAME_SERVER);
        start();
    }

    public DefaultMQProducer getProducer() {
        return producer;
    }

    /**
     * 对象在使用之前必须调用一次,并且只能初始化一次
     */
    public void start() {
        try {
            this.producer.start();
        } catch (MQClientException e) {
            e.printStackTrace();
        }
    }

    /**
     * 一般在应用上下文,使用上下文监听器,进行关闭
     */
    public void shutdown() {
        producer.shutdown();
    }

}